import { ElMessageBox } from 'element-plus'
import { binMsg } from '@/global/api.js'
import { titleCase } from '@/utils/utils.js'
import { selector2, filterList2 } from '@/utils/cascaderUtil.js'
import { findCMC, searchCMC, createCMC, updateCMC, deleteCMC } from '@/services/college.js'

const collegeManageModule = {
  namespaced: true,
  state() {
    return {
      collegeList: [],
      collegeCount: 0,

      majorList: [],
      majorCount: 0,

      classesList: [],
      classesCount: 0,
      // 创建班级时选择所属专业的数据
      college_major_options: []
    }
  },

  mutations: {
    changeCollegeList(state, list) {
      state.collegeList = list
    },
    changeMajorList(state, list) {
      state.majorList = list
    },
    changeClassesList(state, list) {
      state.classesList = list
    },
    changeCollegeCount(state, count) {
      state.collegeCount = count
    },
    changeMajorCount(state, count) {
      state.majorCount = count
    },
    changeClassesCount(state, count) {
      state.classesCount = count
    },
    changeCollege_major_options(state, list) {
      state.college_major_options = list
    },
    clearState(state) {
      state.collegeList = []
      state.majorList = []
      state.classesList = []
      state.college_major_options = []
    }
  },

  actions: {
    // 获取学院、专业
    async getCollegeAndMajor({ commit }, payload) {
      const { data: res } = await findCMC()
      // 将数据修改成合适的格式交给 selector3 进行嵌套
      const newColleges = res.data.data.collegeRes.map((item) => {
        return { id: item.id, label: item.college_name, value: item.college_name }
      })
      const newMajors = res.data.data.majorRes.map((item) => {
        return { id: item.id, label: item.major_name, value: item.major_name, cid: item.cid }
      })

      const selectorList = selector2({
        oneId: 'id', //第一级id
        twoIds: 'id', //第二级id
        twoId: 'cid', //第二级关联第一级的id
        arrOneData: newColleges, //第一级数据
        arrTwoData: newMajors //第二级数据
      })
      // console.log(selectorList)
      commit('changeCollege_major_options', [...filterList2(selectorList)])
    },
    // 查询页面数据
    async searchAction({ commit, state, dispatch }, payload) {
      const { data: res } = await searchCMC(payload)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      const name = titleCase(payload.pageName)
      commit(`change${name}List`, res.data.list)
      commit(`change${name}Count`, res.data.total)
      if (state.college_major_options.length === 0) {
        // console.log(12)
        dispatch('getCollegeAndMajor')
      }
    },
    // 添加
    async createAction({ commit, dispatch }, payload) {
      if (payload.pageName === 'classes') {
        const arr = payload.formData.major_name.split(',')
        payload.formData.college_name = arr[0]
        payload.formData.major_name = arr[1]
      }
      const { data: res } = await createCMC(payload)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      binMsg('success', res.meta.msg)
      dispatch('searchAction', {
        pageName: payload.pageName,
        label: 'class_name',
        value: '',
        page_num: 1,
        page_size: 10
      })
    },
    // 编辑
    async editAction({ commit, state, dispatch }, payload) {
      // console.log(payload)
      if (payload.pageName === 'classes') {
        if (payload.formData?.major_name.includes(',')) {
          const arr = payload.formData.major_name.split(',')
          payload.formData.college_name = arr[0]
          payload.formData.major_name = arr[1]
        }
      }
      // console.log(payload);
      const { data: res } = await updateCMC(payload.formData)
      if (res.meta.status !== 200) return binMsg(res.meta.msg)
      // 替换旧数据
      const newClasses = res.data.data
      const name = titleCase(payload.pageName)
      const classList = [...state[`${payload.pageName}List`]]
      for (let i = 0; i < classList.length; i++) {
        if (classList[i].id === newClasses.id) {
          classList[i] = newClasses
        }
      }
      commit(`change${name}List`, classList)
      binMsg('success', res.meta.msg)
      // 调用 userModule 模块中的 getCollegeAndMajorAndClass，请求最新的班级数据（有问题！）
      // dispatch('userModule/getCollegeAndMajorAndClass', null, { root: true })
    },
    // 删除
    async deleteAction({ commit, dispatch }, payload) {
      try {
        await ElMessageBox.confirm('确认删除该课程吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          draggable: true
        })
        // 发送请求进行删除
        const { data: res } = await deleteCMC(payload.id)
        console.log(res)
        if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
        binMsg('success', res.meta.msg)
        dispatch('searchAction', {
          pageName: payload.pageName,
          label: 'class_name',
          value: '',
          page_num: 1,
          page_size: 10
        })
      } catch (e) {
        binMsg('info', '已取消')
      }
    }
  },
  getters: {
    pageList(state) {
      return (name) => {
        return state[`${name}List`]
      }
    },
    pageCount(state) {
      return (name) => {
        return state[`${name}Count`]
      }
    }
  }
}

export default collegeManageModule
